/***************************************************************
 * Name:      CamMain.cpp
 * Purpose:   Code for Application Frame
 * Author:    Riku Maikola (rpm@ac-mapa.org)
 * Created:   2011-02-17
 * Copyright: Riku Maikola (rpm.ac-mapa.org)
 * License:
 **************************************************************/
#include "wx/wxprec.h"
#include <wx/wx.h>

#include "CamMain.h"

//CamMain::CamMain(wxFrame *frame) : CamMain(frame)
CamMain::CamMain( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style )
{

    this->SetMinSize(wxSize(800,600));

    iPanel = new wxWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
    m_button51 = new wxButton( this, gCycleStart, wxT("Cycle "), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );
    m_button5 = new wxButton( this, ReSetup, wxT("apply setup"), wxDefaultPosition, wxSize( -1,20 ), 0 );

    //****************** MENU *************************//
    MenuBar = new wxMenuBar( 0 );

    //*********************
    ProjectMenu = new wxMenu();
    wxMenuItem* LoadMenu;
    LoadMenu = new wxMenuItem( ProjectMenu, menuLoad, wxString( wxT("Load") ) + wxT('\t') + wxT("F1"), wxEmptyString, wxITEM_NORMAL );
    ProjectMenu->Append( LoadMenu );

    wxMenuItem* SaveMenu;
    SaveMenu = new wxMenuItem( ProjectMenu, menuSave, wxString( wxT("Save") ) + wxT('\t') + wxT("F2"), wxEmptyString, wxITEM_NORMAL );
    ProjectMenu->Append( SaveMenu );

    wxMenuItem* SaveAsMenu;
    SaveAsMenu = new wxMenuItem( ProjectMenu, menuSaveAs, wxString( wxT("Save As") ) + wxT('\t') + wxT("F3"), wxEmptyString, wxITEM_NORMAL );
    ProjectMenu->Append( SaveAsMenu );

    MenuBar->Append( ProjectMenu, wxT("Project") );


    //****************** MENU *************************//
    EditorMenu = new wxMenu();
    wxMenuItem* EditCodeMenu;
    EditCodeMenu = new wxMenuItem( EditorMenu , menuEditCode , wxString( wxT("Code editor") ) + wxT('\t') + wxT("F5"), wxEmptyString, wxITEM_NORMAL );
    EditorMenu->Append( EditCodeMenu );
    wxMenuItem* EditWorkDirMenu;
    EditWorkDirMenu = new wxMenuItem( EditorMenu , menuEditWorkDir , wxString( wxT("Open Work directory") ) + wxT('\t') + wxT("F9"), wxEmptyString, wxITEM_NORMAL );
    EditorMenu->Append( EditWorkDirMenu );
    MenuBar->Append( EditorMenu, wxT("Edit") );



     //****************** BUILD MENU *************************//
    BuildMenu = new wxMenu();
    wxMenuItem* BuildBuildMenu;
    BuildBuildMenu = new wxMenuItem( BuildMenu , menuBuild , wxString( wxT("Build") ) + wxT('\t') + wxT("F10"), wxEmptyString, wxITEM_NORMAL );
    BuildMenu->Append( BuildBuildMenu );

    wxMenuItem* BuildBuildRunMenu;
    BuildBuildRunMenu = new wxMenuItem( BuildMenu , menuBuildRun , wxString( wxT("Build/Run") ) + wxT('\t') + wxT("F11"), wxEmptyString, wxITEM_NORMAL );
    BuildMenu->Append( BuildBuildRunMenu );

    wxMenuItem* BuildRunMenu;
    BuildRunMenu = new wxMenuItem( BuildMenu , menuRun , wxString( wxT("Run") ) + wxT('\t') + wxT("F12"), wxEmptyString, wxITEM_NORMAL );
    BuildMenu->Append( BuildRunMenu );
    MenuBar->Append( BuildMenu, wxT("Build") );




    //*********************


    ViewMenu = new wxMenu();
    ViewLookFromMenu = new wxMenu();
    wxMenuItem* ViewLookAtXYMenu;
    ViewLookAtXYMenu = new wxMenuItem( ViewLookFromMenu, ViewLookAtXY, wxString( wxT("XY") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookFromMenu->Append( ViewLookAtXYMenu );

    wxMenuItem* ViewLookAtYZMenu;
    ViewLookAtYZMenu = new wxMenuItem( ViewLookFromMenu, ViewLookAtYZ, wxString( wxT("YZ") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookFromMenu->Append( ViewLookAtYZMenu );

    ViewMenu->Append( -1, wxT("LookFrom"), ViewLookFromMenu );

    ViewLookAtMenu = new wxMenu();
    wxMenuItem* m_G54;
    m_G54 = new wxMenuItem( ViewLookAtMenu, LookAtG54, wxString( wxT("G54") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookAtMenu->Append( m_G54 );

    wxMenuItem* m_G55;
    m_G55 = new wxMenuItem( ViewLookAtMenu, LookAtG55, wxString( wxT("G55") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookAtMenu->Append( m_G55 );

    wxMenuItem* m_G56;
    m_G56 = new wxMenuItem( ViewLookAtMenu, LookAtG56, wxString( wxT("G56") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookAtMenu->Append( m_G56 );

    wxMenuItem* m_G57;
    m_G57 = new wxMenuItem( ViewLookAtMenu, LookAtG57, wxString( wxT("G57") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookAtMenu->Append( m_G57 );

    wxMenuItem* m_G58;
    m_G58 = new wxMenuItem( ViewLookAtMenu, LookAtG58, wxString( wxT("G58") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookAtMenu->Append( m_G58 );

    wxMenuItem* m_G59;
    m_G59 = new wxMenuItem( ViewLookAtMenu, LookAtG59, wxString( wxT("G59") ) , wxEmptyString, wxITEM_NORMAL );
    ViewLookAtMenu->Append( m_G59 );

    ViewMenu->Append( -1, wxT("LookAt"), ViewLookAtMenu );

    MenuBar->Append( ViewMenu, wxT("View") );

    ImagesMenu = new wxMenu();
    wxMenuItem* LoadImageMenu;
    LoadImageMenu = new wxMenuItem( ImagesMenu, loadImages, wxString( wxT("Load") ) , wxEmptyString, wxITEM_NORMAL );
    ImagesMenu->Append( LoadImageMenu );

    wxMenuItem* SaveImageMenu;
    SaveImageMenu = new wxMenuItem( ImagesMenu, saveImages, wxString( wxT("Save as dxf") ) , wxEmptyString, wxITEM_NORMAL );
    ImagesMenu->Append( SaveImageMenu );

    wxMenuItem* m_separator3;
    m_separator3 = ImagesMenu->AppendSeparator();

    wxMenuItem* DeselectAllMenu;
    DeselectAllMenu = new wxMenuItem( ImagesMenu, imageDeselectALL, wxString( wxT("deselect all") ) , wxEmptyString, wxITEM_NORMAL );
    ImagesMenu->Append( DeselectAllMenu );

    wxMenuItem* m_separator4;
    m_separator4 = ImagesMenu->AppendSeparator();

    wxMenuItem* DeleteSelected;
    DeleteSelected = new wxMenuItem( ImagesMenu, imageDelElement, wxString( wxT("delete selected") ) , wxEmptyString, wxITEM_NORMAL );
    ImagesMenu->Append( DeleteSelected );

    wxMenuItem* m_separator111;
    m_separator111 = ImagesMenu->AppendSeparator();

    wxMenuItem* ImageMenuClear;
    ImageMenuClear = new wxMenuItem( ImagesMenu, imageMenuClear, wxString( wxT("Clear image") ) , wxEmptyString, wxITEM_NORMAL );
    ImagesMenu->Append( ImageMenuClear );

    MenuBar->Append( ImagesMenu, wxT("Images") );

    G_PathMenu = new wxMenu();
    wxMenuItem* G_PathGetPlateMenu;
    G_PathGetPlateMenu = new wxMenuItem( G_PathMenu, G_PathGetPlate, wxString( wxT("Get plate from Image") ) , wxEmptyString, wxITEM_NORMAL );
    G_PathMenu->Append( G_PathGetPlateMenu );

    wxMenuItem* G_PathShowMenu;
    G_PathShowMenu = new wxMenuItem( G_PathMenu, G_PathShow, wxString( wxT("Hide") ) , wxEmptyString, wxITEM_NORMAL );
    G_PathMenu->Append( G_PathShowMenu );

    MenuBar->Append( G_PathMenu, wxT("Gpath") );

    this->SetMenuBar( MenuBar );

    statusBar = this->CreateStatusBar( 3, wxST_SIZEGRIP, wxID_ANY );

    // Connect Events
    this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( CamMain::OnClose ) );
    iPanel->Connect( wxEVT_SIZE, wxSizeEventHandler( CamMain::iOnSize ), NULL, this );
    m_button51->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );
    m_button5->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );


    this->Connect( LoadMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenu ) );
    this->Connect( SaveMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenu ) );
    this->Connect( SaveAsMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenu ) );

    //   Edit Menu
    this->Connect( EditCodeMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuEdit ) );
    this->Connect( EditWorkDirMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuEdit ) );
    //   Build Menu
    this->Connect( BuildBuildMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuBuild ) );
    this->Connect( BuildBuildRunMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuBuild ) );
    this->Connect( BuildRunMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuBuild ) );


    //viewmenu
    this->Connect( ViewLookAtXYMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( ViewLookAtYZMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( m_G54->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( m_G55->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( m_G56->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( m_G57->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( m_G58->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( m_G59->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Connect( LoadImageMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Connect( SaveImageMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Connect( DeselectAllMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Connect( DeleteSelected->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Connect( ImageMenuClear->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Connect( G_PathGetPlateMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuGpath ) );
    this->Connect( G_PathShowMenu->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuGpath ) );
    //***//


    //**********************************************************************************************************//
    //**
    //**                CLI -
    CliWindow = new wxWindow( this , wxID_HIGHEST ,wxPoint(0,200),wxSize(200,100),wxBORDER_DOUBLE,_("CLI window"));
    CliWindow->Hide();
    iPAST = new wxTextCtrl( CliWindow , wxID_ANY, wxEmptyString, wxPoint(0,0) , wxSize( 200,80 ), wxTE_MULTILINE|wxTE_READONLY|wxRAISED_BORDER );
    iCLI  = new wxTextCtrl( CliWindow , wxID_ANY, wxEmptyString, wxPoint(0,80) , wxSize( 200,20 ), wxTE_PROCESS_ENTER );
    iCLI->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( CamMain::iEXE ), NULL, this );


    //**********************************************************************//
    //**                           Simulation                             **//
    //**********************************************************************//
    SimulationWindow = new wxWindow( this , wxID_HIGHEST ,wxPoint(0,0),wxSize(800,20),wxBORDER_DOUBLE,_("TOOLWINDOW"));

    SimulationInfo= new wxTextCtrl(SimulationWindow, wxID_HIGHEST ,wxT(""), wxPoint(0,20), wxSize(200,60) , wxTE_MULTILINE  | wxTE_READONLY | wxTE_RICH | wxTE_DONTWRAP , wxDefaultValidator, wxTextCtrlNameStr);
    SimulationPlay = new wxButton( SimulationWindow , gPLAY, wxT(">"), wxPoint(0,0) , wxSize(20,20) , wxBU_EXACTFIT );
    SimulationStop = new wxButton( SimulationWindow , gSTOP, wxT("||"), wxPoint(20,0), wxSize(20,20), wxBU_EXACTFIT );
    SimulationPosition = new wxSlider( SimulationWindow, wxID_ANY, 0, 0, 1, wxPoint(40,0), wxSize(800,20), wxSL_HORIZONTAL );

    SimulationPlay->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );
    SimulationStop->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );

    SimulationPosition->Connect( wxEVT_SCROLL_TOP, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Connect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );


    //************************************************************************************************//
    int args[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 16, 0};
    Canvas = new mCanvas(iPanel, 0, wxPoint(0,0),wxSize(0, 0), wxBORDER_NONE, _("some text"),args);

    //*******************************************************************************************//
    Canvas->Connect( wxEVT_PAINT,        wxPaintEventHandler( CamMain::iPaint ), NULL, this );

    Canvas->Connect( wxEVT_KEY_DOWN,     wxKeyEventHandler( CamMain::iKeyDOWN ), NULL, this );
    Canvas->Connect( wxEVT_KEY_UP,       wxKeyEventHandler( CamMain::iKeyUP ), NULL, this );
    Canvas->Connect( wxEVT_LEFT_DOWN,    wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_LEFT_UP,      wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_MIDDLE_DOWN,  wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_MIDDLE_UP,    wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_RIGHT_DOWN,   wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_RIGHT_UP,     wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_MOTION,       wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_LEFT_DCLICK,  wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_MIDDLE_DCLICK,wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_RIGHT_DCLICK, wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Connect( wxEVT_MOUSEWHEEL,   wxMouseEventHandler( CamMain::iMouse ), NULL, this );

    this->Connect( wxEVT_SIZE, wxSizeEventHandler(CamMain::SizeFrame),NULL,this);

    //*******************************************************************************************//
    m_timer.SetOwner(this);
    this->Connect( wxEVT_TIMER, wxTimerEventHandler( CamMain::OnTimer ), NULL, this );


    //*******************************************************************************************//
    update_timer.SetOwner(this);
    this->Connect( wxEVT_TIMER, wxTimerEventHandler( CamMain::OnTimerUpdate ), NULL, this );
}
CamMain::~CamMain()
{
    // Disconnect Events
    this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( CamMain::OnClose ) );
    iPanel->Disconnect( wxEVT_SIZE, wxSizeEventHandler( CamMain::iOnSize ), NULL, this );
    iCLI->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( CamMain::iEXE ), NULL, this );
    m_button51->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );
    SimulationPlay->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );
    SimulationStop->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_TOP, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_BOTTOM, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_LINEUP, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_PAGEUP, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    SimulationPosition->Disconnect( wxEVT_SCROLL_CHANGED, wxScrollEventHandler( CamMain::OnScroll ), NULL, this );
    m_button5->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CamMain::BUTTON ), NULL, this );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenu ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenu ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenu ) );

    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuEdit ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuBuild ) );

    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuView ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuImage ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuGpath ) );
    this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( CamMain::OnMenuGpath ) );
    //****//
    Canvas->Disconnect( wxEVT_PAINT,         wxPaintEventHandler( CamMain::iPaint ), NULL, this );

    Canvas->Disconnect( wxEVT_KEY_DOWN,     wxKeyEventHandler( CamMain::iKeyDOWN ), NULL, this );
    Canvas->Disconnect( wxEVT_KEY_UP,       wxKeyEventHandler( CamMain::iKeyUP ), NULL, this );

    Canvas->Disconnect( wxEVT_LEFT_DOWN,     wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_LEFT_UP,       wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_MIDDLE_DOWN,   wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_MIDDLE_UP,     wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_RIGHT_DOWN,    wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_RIGHT_UP,      wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_MOTION,        wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_LEFT_DCLICK,   wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_MIDDLE_DCLICK, wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_RIGHT_DCLICK,  wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_LEAVE_WINDOW,  wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_ENTER_WINDOW,  wxMouseEventHandler( CamMain::iMouse ), NULL, this );
    Canvas->Disconnect( wxEVT_MOUSEWHEEL,    wxMouseEventHandler( CamMain::iMouse ), NULL, this );

    this->Disconnect( wxEVT_TIMER,         wxTimerEventHandler( CamMain::OnTimer ), NULL, this );
    this->Disconnect( wxEVT_TIMER,         wxTimerEventHandler( CamMain::OnTimerUpdate ), NULL, this );

    std::cout << "\nexiting UI\n\n";
}
//****************************************************************************************************//
//**
//**            SIM CONTROL
//**
//****************************************************************************************************//
void CamMain::OnSIM()
{
    /*SimulationPosition->SetValue( int(SIM.aika*1000) );
    SimulationInfo->ChangeValue( wxString::Format(_("%1.0fm%2.0fs/%1.0fm%2.0fs\n f=%1.3f\n\n  x=%1.3f\n y=%1.3f\n z=%1.3f\n"),
                                 floor(SIM.aika),((SIM.aika)-floor(SIM.aika))*60,floor(SIM.GetCycleTime()),
                                 (SIM.GetCycleTime() -floor(SIM.GetCycleTime()))*60,SIM.feed , SIM.pos.x,SIM.pos.y,SIM.pos.z));*/
}

//****************************************************//
void CamMain::OnScroll( wxScrollEvent& event )
{
    //SIM.SetTime(double(SimulationPosition->GetValue())/1000);
    OnSIM();
    Canvas->Refresh();

}
void CamMain::OnTimer(wxTimerEvent& event)
{
    SIM.Tick();
    OnSIM();

    Canvas->Refresh();
}

//----------------------------------------------
void CamMain::OnTimerUpdate(wxTimerEvent& event)
{
    Uptime++;
    LineChange("reg",0,"testi");
    //check if tool path is available
    if(FileIsUpdated(&TimeOfUpdateOfSim, mS( WORKDIR.mb_str().data(),"/sim.out","END")))
    {
         std::cout << "sim updated\n";
    }

    //check for assets
    unsigned char isFile =0x8;
    DIR           *d;
    struct dirent *dir;
    std::vector<string> dirlist;
    int i=0;

    d = opendir(mS(WORKDIR.mb_str().data(),"/assets","END").c_str());
    if (d)
    {
        //Read current directory
        while(dir = readdir(d))
        {
            std::string n = dir->d_name;
            if ( dir->d_type == isFile)
                if(n.rfind("~")==std::string::npos)
                 dirlist.push_back(dir->d_name);
        }
        std::sort( dirlist.begin(), dirlist.end() );
        while(dirlist.size()<AssDir.size())AssDir.pop_back();   //delete from end..

        //check for changes
        for(uint a=0;a<dirlist.size();a++)
        {
            //std::cout << a  << "  loop " << "\n";
            if((a+1)>AssDir.size())
            {
                Asset neW;
                neW.file = mS(WORKDIR.mb_str().data(),"/assets/",dirlist[a].c_str(),"END");
                AssDir.push_back(neW);
                std::cout << dirlist[a] << a << "   added new " << neW.file  << "\n";
            }

            if(mS(WORKDIR.mb_str().data(),"/assets/",dirlist[a].c_str(),"END") == AssDir[a].file )
            {
                if(FileIsUpdated(&AssDir[a].UpdateTime,  AssDir[a].file))
                {
                    std::cout << "asset need updating\n";
                }
            }
            else
            {
                AssDir[a].file = mS(WORKDIR.mb_str().data(),"/assets/",dirlist[a].c_str(),"END");
                AssDir[a].UpdateTime = 0;
            };
        }
        closedir(d);
    }
}

//***********************************************//
void CamMain::Initation()
{
    //EXE( "here2" , "here3" , "END" );
    //test

    //mPoint TEST(1,1,1);
    //TEST.RotateY(0.1);
    //printf("%f %f %f\n",TEST.x,TEST.y,TEST.z);

    /*void (*foo[10])();
    foo[0] = &rin1;
    foo[1] = &rin2;
    foo[0]();
    foo[1]();*/

    Canvas->Init();

    //***********************************//
   // Load(loadproject);

    E(SETUP);

    //***//
    Canvas->LookAt();
    Canvas->mv_matrix = vmath::translate( 0.0f , 0.0f , 0.0f);

    //TOOLHUD
    Canvas->vbo[GRIDVBO].show=true;
    DB.Clear();

    for(double a=-500;a<510;a=a+20)
    {
        DB.Vert(mP(-500,   a,0) ,0.4,0.4,0.9,1, mP(0,0,0),0);
        DB.Vert(mP( 500,   a,0) ,0.4,0.4,0.9,1, mP(0,0,0),0);
        DB.Vert(mP(   a,-500,0) ,0.4,0.4,0.9,1, mP(0,0,0),0);
        DB.Vert(mP(   a, 500,0) ,0.4,0.4,0.9,1, mP(0,0,0),0);
    }


    DB.Vert(mP(   0, 0,-100) ,0.4,0.4,0.4,1, mP(0,0,0),0);
    DB.Vert(mP(   0, 0,100) ,0.4,0.4,0.4,1, mP(0,0,0),0);


    DB.Set(GL_LINES,1,true);
    Canvas->Update( GRIDVBO , &DB );

    iNum=1;
    //Canvas->Add(0,NUMBERS(iNum).ConvertToImage());
    Canvas->Refresh();
    update_timer.Start(500);

    uint a= chdir( WORKDIR.mb_str() );

}

//***************************************//
//**
//***********************************************//
void CamMain::OnMenu( wxCommandEvent& event )
{
    if(event.GetId()==menuLoad)
    {
/*        wxFileDialog LoadFileDialog(this, _("Load Project"), _(""),PATH,_("cam files (*.cam)|*.cam"), wxFD_OPEN|wxFD_FILE_MUST_EXIST);
        if (LoadFileDialog.ShowModal() == wxID_CANCEL)
            return;     // the user changed idea...

        //
        PATH = LoadFileDialog.GetPath();
        EXE( "rm -rf " , WORKDIR.mb_str().data() , "\n" ,"END");
        WORKDIR = wxString::FromUTF8(newDir("/dev/shm/maicam_","END").c_str());
        EXE( "cd " , WORKDIR.char_str().data() , "\ntar -xf " , PATH.mb_str().data() , "END");
        SetTitle(PATH);*/
        return;
    }

    //SAVE
    else if(event.GetId()==menuSave)
    {
       // EXE( "cd " , WORKDIR.mb_str().data() , "\ntar -cf " , PATH.mb_str().data() , " *\n" , "END" );
        return;
    }

    else if(event.GetId()==menuSaveAs)
    {
    /*    wxFileDialog SaveFileDialog(this, _("Save project"), _(""), _(""),_("cam files (*.cam)|*.cam"),wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
        SaveFileDialog.SetPath(PATH);
        if (SaveFileDialog.ShowModal() == wxID_CANCEL)
            return;     // the user changed idea...

        PATH =  SaveFileDialog.GetPath();
        SetTitle(PATH);

        EXE( "cd " , WORKDIR.mb_str().data() , "\ntar -cf " , PATH.mb_str().data() , " *\n" , "END" );*/
        return;
    }
}
//
void CamMain::OnMenuEdit( wxCommandEvent& event )
{
    if(event.GetId()==menuEditCode) uint a = system( "gedit CODE &\n" );
    if(event.GetId()==menuEditWorkDir) uint a = system( "thunar  &\n");
}
//********************************************//
//
void CamMain::OnMenuBuild( wxCommandEvent& event )
{
    if(event.GetId()==menuRun) uint a = system("~/MAICAM/bin/simulator &\n");
}


//*********************************************//
//***              View Menu                 **//
//*********************************************//
void CamMain::OnMenuView( wxCommandEvent& event )
{
    if(event.GetId()==ViewLookAtXY)
    {
//        Canvas->rz = 0;
        //      Canvas->rx = 0;
        //    Canvas->Refresh();
        return;
    }
    else if(event.GetId()==ViewLookAtYZ)
    {
        //     Canvas->rz = -90;
        //     Canvas->rx = 90;
        Canvas->Refresh();
        return;
    }
    else if(event.GetId()==LookAtG54)
    {
        //Canvas->lx = 0;
        //Canvas->ly = 0;
        //Canvas->lz = 0;
        Canvas->Refresh();
        return;
    }
    else if(event.GetId()==LookAtG55)
    {
        //Canvas->lx = SIM.GetV(G54_X)-SIM.GetV(G55_X);
        //Canvas->ly = SIM.GetV(G54_Y)-SIM.GetV(G55_Y);
        //Canvas->lz = SIM.GetV(G54_Z)-SIM.GetV(G55_Z);
        Canvas->Refresh();
        return;
    }
    else if(event.GetId()==LookAtG56)
    {

        Canvas->Refresh();
        return;
    }
    else if(event.GetId()==LookAtG57)
    {

        Canvas->Refresh();
        return;
    }
    else if(event.GetId()==LookAtG58)
    {

        Canvas->Refresh();
        return;
    }
    else if(event.GetId()==LookAtG59)
    {

        Canvas->Refresh();
        return;
    }
}
//***************************************************//
//**                  IMAGE menu                   **//
//***************************************************//
void CamMain::OnMenuImage( wxCommandEvent& event )
{
    if(event.GetId()==loadImages)
    {
        wxFileDialog LoadFileDialog(this, _("Load image"), _(""),_("") ,_("files (*.dxf;*.stl)|*.dxf;*.stl"), wxFD_OPEN|wxFD_FILE_MUST_EXIST);

        if (LoadFileDialog.ShowModal() == wxID_CANCEL)
            return;

        uint a = system( ( "\n ~/MAICAM/bin/OpenAsset '" + newFile( WORKDIR.mb_str().data() , "/assets/" , "END" ) + "' '" +  LoadFileDialog.GetPath().mb_str().data() + "'").c_str() );

        return;
    }

    else if(event.GetId()==saveImages)
    {
       /* wxFileDialog SaveFileDialog(this, _("Save Image as dxf"), _(""), _(""),_("dxf files (*.dxf)|*.dxf"),wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
        SaveFileDialog.SetPath(PATH);
        if (SaveFileDialog.ShowModal() == wxID_CANCEL)
            return;     // the user changed idea...
*/
        return;
    }
    else if(event.GetId()==imageDeselectALL)
    {
        I[iNum].DeselectAll();
        return;
    }
    else if(event.GetId()==imageDelElement)
    {
        I[iNum].Del();
        return;
    }
    else if(event.GetId()==imageMenuClear)
    {
        I[iNum].Clear();
        return;
    }
    iPanel->Refresh();
}

void CamMain::iOnSize( wxSizeEvent& event )
{
    Canvas->W = iPanel->GetSize().GetWidth();
    Canvas->H = iPanel->GetSize().GetHeight();
    Canvas->Refresh();
}

//**************************
//***   view menu
//**************************
void CamMain::OnMenuGpath( wxCommandEvent& event )
{
    if(event.GetId()==G_PathShow)
    {
        //std::cout << event.GetEventObject(). << "\n";
        if( G_PathMenu->GetLabel(G_PathShow).IsSameAs(_("Hide")))
        {
            G_PathMenu->SetLabel(G_PathShow,_("show"));
            Canvas->vbo[SIMVBO].show = false;
        }
        else
        {
            G_PathMenu->SetLabel(G_PathShow,_("Hide"));
            Canvas->vbo[SIMVBO].show = true;
        }
        return;
    }
}
//********************************************//
//**                                        **//
//********************************************//
void CamMain::iEXE( wxCommandEvent& event )
{
    E(iCLI->GetValue());
    wxString AS =  iCLI->GetValue();
    AS << _("\n");
    iPAST->AppendText( AS );
    iCLI->Clear();
    CliWindow->Hide();
    Canvas->Refresh();
}

//********************************************//
//                  CAD                       //
//********************************************//
void CamMain::iWheel( wxMouseEvent& event )
{
    if(event.m_wheelRotation>0)
    {
        iNum++;
        if(iNum==numImages)iNum=numImages-1;
        //Canvas->Add(0,NUMBERS(iNum).ConvertToImage());

    }
    else  if(event.m_wheelRotation<0)
    {
        iNum--;
        if(iNum<0)iNum=0;
        //Canvas->Add(0,NUMBERS(iNum).ConvertToImage());
    }
    Canvas->Refresh();
}
//****************************************/
//**
//****************************************/
void CamMain::iKeyDOWN( wxKeyEvent& event )
{
    if(event.GetKeyCode()==306)Shift=true;
    if(event.GetKeyCode()==308)Ctrl=true;
    if(event.GetKeyCode()==307)Alt=true;

    //Layer select pageup pagedown
    if(event.GetKeyCode()==366)
    {
        SetImageUp();
        //Canvas->Add(0,NUMBERS(iNum).ConvertToImage());

    }
    else if(event.GetKeyCode()==367)
    {
        SetImageDown();
        //Canvas->Add(0,NUMBERS(iNum).ConvertToImage());
    }



    if(!Ctrl&&!Shift&&!Alt)
    {
        if(event.GetKeyCode()==344)
        {
/*            wxFileDialog LoadFileDialog(this, _("Load image"), _(""),PATH ,_("files (*.dxf;*.stl)|*.dxf;*.stl"), wxFD_OPEN|wxFD_FILE_MUST_EXIST);

            if (LoadFileDialog.ShowModal() == wxID_CANCEL)
                return;     // the user changed idea...

            int nb = iNum;

            I[iNum].Clear();
            LoadImage( &I[iNum] , LoadFileDialog.GetPath());*/

            return;
        }

        else if(event.GetKeyCode()==69)
        {
            CliWindow->Show();
            CliWindow->SetPosition(  event.GetPosition() - wxPoint(15,15) );
            iCLI->SetFocus();

            return;

        }

        else if(event.GetKeyCode()==345)
        {
        /*    wxFileDialog SaveFileDialog(this, _("Save Image as dxf"), _(""), _(""),_("dxf files (*.dxf)|*.dxf"),wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
            SaveFileDialog.SetPath(PATH);
            if (SaveFileDialog.ShowModal() == wxID_CANCEL)
                return;     // the user changed idea...*/

            //I[iNum].Save( SaveFileDialog.GetPath() );

            return;
        }
        else if(event.GetKeyCode()==329)
        {

            /*if(Canvas->ortho) Canvas->ortho= false;
            else Canvas->ortho= true;*/
            Refresh();
            return;
        }
    }

    //ONLY CTRL key pressed
    if(Ctrl&&!Shift&&!Alt)
    {
        if(event.GetKeyCode()==67)      I[iNum].MakeChain(); //make image to chain type
        else if(event.GetKeyCode()==70) I[iNum].Flip();      //Flip chain..
        else if(event.GetKeyCode()==80) I[iNum].SelectConnected();
        else if(event.GetKeyCode()==127)I[iNum].Clear();
        else if(event.GetKeyCode()==65) I[iNum].SelectALL();
        else if(event.GetKeyCode()==65) I[iNum].SelectALL();
        else if(event.GetKeyCode()==73) I[iNum].SetType(m_Image);

        //MoVE
        else if(event.GetKeyCode()==333 || event.GetKeyCode()==330 ||  event.GetKeyCode()==327)I[iNum].MoveRight();
        else if(event.GetKeyCode()==331 || event.GetKeyCode()==328 ||  event.GetKeyCode()==325)I[iNum].MoveLeft();
        else if(event.GetKeyCode()==325 || event.GetKeyCode()==326 ||  event.GetKeyCode()==327)I[iNum].MoveDown();
        else if(event.GetKeyCode()==331 || event.GetKeyCode()==332 ||  event.GetKeyCode()==333)I[iNum].MoveUp();
        else if(event.GetKeyCode()==329 || event.GetKeyCode()==326 ||  event.GetKeyCode()==332)I[iNum].MoveVerticalCenter();
        else if(event.GetKeyCode()==329 || event.GetKeyCode()==328 ||  event.GetKeyCode()==330)I[iNum].MoveHorizontalCenter();

        Canvas->Refresh();
        return;
    }

    //************************************************************************
    //**
    //************************************************************************
    if(!Ctrl&&Shift&&!Alt)
    {
        if(event.GetKeyCode()==127)I[iNum].Del();
    }

    //*************************************************************************
    //** ALT
    //*************************************************************************
    if(!Ctrl&&!Shift&&Alt)
    {
        //ALT+a  deselect all
        if(event.GetKeyCode()==65)I[iNum].DeselectAll();
    }
    Canvas->Refresh();

    std::cout << event.GetKeyCode() << "\n";
}
void CamMain::iKeyUP( wxKeyEvent& event )
{
    if(event.GetKeyCode()==306)Shift=false;
    if(event.GetKeyCode()==308)Ctrl=false;
    if(event.GetKeyCode()==307)Alt=false;
}


//****************************************/
//**
//****************************************/
void CamMain::iMouse( wxMouseEvent& event )
{
    if( MP != event.GetPosition() )
    {
        MP = event.GetPosition();
        Canvas->SetFocus();
        CliWindow->Hide();
    }

    //set key focus
    if(event.RightUp())
    {
        //
        if(!CanvasMouseMove)
        {
            wxMenu mnu;
            mnu.Append(f_Copy         , 	_("Copy"));
            mnu.Append(f_Copy_selected, 	_("Copy selected"));
            mnu.Append(f_Paste        , 	_("Paste"));
            mnu.Append(f_Clear        , 	_("Clear"));

            mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&CamMain::OnPopupClick, NULL, this);
            PopupMenu(&mnu);
        }

        CanvasMouseMove=false;
    }
    //reset
    if(event.ButtonDown(wxMOUSE_BTN_LEFT))
    {
        MX = double(event.m_x)-(Canvas->W/2);
        MY = (Canvas->H/2)-double(event.m_y);

//        LMX = (MX-Canvas->lx)/Canvas->ls;
//        LMY = (MY-Canvas->ly)/Canvas->ls;

        //*************//
        uint pi=Canvas->PICK( iNum , event.m_x,Canvas->H-event.m_y);
        if((pi+1)>I[iNum].Size())return;
        I[iNum].Select( pi );

        statusBar->SetStatusText( wxString::Format(_("%d -> "),pi) );
        Canvas->Refresh();
    }

    if(event.ButtonDown(wxMOUSE_BTN_MIDDLE))
    {
        MMX = double(event.m_x);
        MMY = double(event.m_y);
    }

    if(event.ButtonDown(wxMOUSE_BTN_RIGHT))
    {
        MMX = double(event.m_x);
        MMY = double(event.m_y);
    }

    //MOVE with rihght mouse button....
    /*    if(Canvas->ortho)
        {
            if(event.Dragging() && event.LeftIsDown())
            {
                Canvas->vbo[PAVBO].show=true;

                DB.Clear();
              DB.Vert(mP((MX-Canvas->lx)/Canvas->ls,(MY-Canvas->ly)/Canvas->ls),0.7,0.7,0.7,0.2);
                DB.Vert(mP((MX-Canvas->lx)/Canvas->ls,((Canvas->H/2)-double(event.m_y)-Canvas->ly)/Canvas->ls),0.7,0.7,0.7,0.3);
                DB.Vert(mP((double(event.m_x)-(Canvas->W/2)-Canvas->lx)/Canvas->ls,((Canvas->H/2)-double(event.m_y)-Canvas->ly)/Canvas->ls),0.5,0.5,0.5,0.3);
                DB.Vert(mP((double(event.m_x)-(Canvas->W/2)-Canvas->lx)/Canvas->ls,(MY-Canvas->ly)/Canvas->ls),0.6,0.6,0.6,0.2);

                DB.Set( GL_QUADS , 0 , true);

                Canvas->Update( PAVBO , &DB );
                Canvas->Refresh();
            };
            if(event.LeftUp())
            {
                I[iNum].SelectArea( mP( LMX,LMY) , mP( (double(event.m_x)-(Canvas->W/2)-Canvas->lx)/Canvas->ls,(((Canvas->H/2)-double(event.m_y)-Canvas->ly)/Canvas->ls)) );
                Canvas->vbo[PAVBO].show=false;
                Canvas->Refresh();
            };

        };*/

    //MOVE with right mouse button....
    if(event.Dragging() && event.RightIsDown())
    {
        CanvasMouseMove=true;

        double DX = MMX-double(event.m_x);
        double DY = MMY-double(event.m_y);
        MMX = double(event.m_x);
        MMY = double(event.m_y);

        Canvas->LookMove(DX,-DY);

        Canvas->LookAt();
        Canvas->Refresh();
    };

    //MOVE with middle mouse button....
    if(event.Dragging() && event.MiddleIsDown())
    {
        double DX = MMX-double(event.m_x);
        double DY = MMY-double(event.m_y);
        MMX = double(event.m_x);
        MMY = double(event.m_y);

        Canvas->LookDirection( DX/1000 , DY/1000 );
        Canvas->LookAt();
        Canvas->Refresh();
    };
    if(event.m_wheelRotation>0)
    {
        Canvas->L += Canvas->vL*10;
        Canvas->LookAt();
        Canvas->Refresh();
    };
    if(event.m_wheelRotation<0)
    {
        Canvas->L -= Canvas->vL*10;
        Canvas->LookAt();
        Canvas->Refresh();
    };
    //Canvas->Refresh();
}

/*******************************************************/
/**                                                    */
/*******************************************************/
void CamMain::BUTTON( wxCommandEvent& event )
{
    //************************************************************//
    //*********     g code     handler BUILD   *******************//
    //************************************************************//
    if(event.GetId()==gCycleStart)
    {
        /*CODE = CodeEditBox->GetValue();
        SIM.CYCLE(CODE);

        DB.Clear();
        DB.vbuf = SIM.I;

        DB.Set( GL_LINE_STRIP , 0 , true);

        Canvas->Update( SIMVBO , &DB );

        Canvas->Refresh();
        SimulationPosition->SetMax(int(SIM.GetCycleTime()*1000   ));
        SimulationInfo->ChangeValue(SIM.MSG);*/

        return;
    }

    //********************//
    if(event.GetId()==gPLAY)
    {
       /* CODE = CodeEditBox->GetValue();
        SIM.CYCLE(CODE);

        DB.Clear();
        DB.vbuf = SIM.I;

        DB.Set( GL_LINE_STRIP , 0 , true);

        Canvas->Update( SIMVBO , &DB );

        Canvas->Refresh();
        SimulationPosition->SetMax(int(SIM.GetCycleTime()*1000   ));
        SimulationInfo->ChangeValue(SIM.MSG);

        m_timer.Start(40);*/
        return;
    }
    if(event.GetId()==gSTOP)
    {
        m_timer.Stop();
        return;
    }


    //************************************************************//
    //*********              handler BUILD        ****************//
    //************************************************************//
    if(event.GetId()==gBuild)
    {

       /* int ulos = system("/opt/MAICAM/c/simulator &");
        std::cout << " welcome  ****************\n";

        SCRIPT = ScriptEditBox->GetValue();
        E(SCRIPT);
        CodeEditBox->ChangeValue(CODE);
        CODE = CodeEditBox->GetValue();
        SIM.CYCLE(CODE);

        // Canvas->Update(SIM.VBO,&SIM.I,GL_LINE_STRIP);

        SimulationPosition->SetMax(int(SIM.GetCycleTime()*1000   ));
        Canvas->Refresh();*/
        return;
    }

    //****************************************************//
    //**
    //****************************************************//
    if(event.GetId()==ReSetup)
    {
        SETUP = SetupEditBox->GetValue();
        E(SETUP);
    }

    //*****************************************************//
    //***********         TOOL                  ***********//
    //*****************************************************//
    else if(event.GetId()==tGetImage)
    {
        I[startToolPos+tNum].Clear();
        I[iNum].Copy( &I[startToolPos+tNum],mP(0,0));

        I[startToolPos+tNum].Lathe(&DB);
        Canvas->Update( startToolPos+tNum , &DB );

        return;
    }

    if(event.GetId()==tLoad)
    {
        wxFileDialog LoadFileDialog(this, _("Load Tool"),_(""),_(""),_(".tool files (*.tool)|*.tool"), wxFD_OPEN|wxFD_FILE_MUST_EXIST);
        LoadFileDialog.SetDirectory(tPATH);
        if (LoadFileDialog.ShowModal() == wxID_CANCEL)
            return;     // the user changed idea...

        I[startToolPos+tNum].FileName = LoadFileDialog.GetPath();

        I[startToolPos+tNum].Clear();
        LoadTool(LoadFileDialog.GetPath());

        //***********//
        I[startToolPos+tNum].Lathe(&DB);
        Canvas->Update( startToolPos+tNum , &DB );

        return;
    }
    if(event.GetId()==tSave)
    {
        wxFileDialog SaveFileDialog(this, _("Save tool"), _(""), _(""),_("tool files (*.tool)|*.tool"),wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
        SaveFileDialog.SetDirectory(tPATH);
        if (SaveFileDialog.ShowModal() == wxID_CANCEL)
            return;     // the user changed idea...
        I[startToolPos+tNum].FileName = SaveFileDialog.GetPath();
        SaveTool( SaveFileDialog.GetPath() );
        return;
    }
}
void CamMain::iPaint(wxPaintEvent& event)
{
    Canvas->ViewPort();
    Canvas->LookAt();

    for(uint a=1; a<numImages; a++)
    {
        if(I[a].Refresh(&DB))Canvas->Update(a, &DB );
        Canvas->Render(a);
    }

    Canvas->Render( PAVBO );
    Canvas->Render( SIMVBO );
    Canvas->Render( startToolPos + SIM.tool , SIM.pos );

    Canvas->Render( GRIDVBO );
    //if(Desktop==gDesktopTool)Canvas->window(startToolPos+tNum, 5 , I[startToolPos+tNum].H.x,I[startToolPos+tNum].H.y+100);

    Canvas->SwapBuffers();
}

void CamMain::SizeFrame(wxSizeEvent& event)
{
    //Canvas??
    iPanel->SetSize(wxSize(this->GetSize()));
    Canvas->SetSize(wxSize(this->GetSize()));

    //Setup
    SimulationWindow->SetSize(wxSize(this->GetSize().x,20));
    SimulationPosition->SetSize(wxSize(this->GetSize().x-40,20));
    SimulationWindow->SetPosition(wxPoint(0,this->GetSize().y-SimulationWindow->GetSize().y-46));

    Canvas->proj_matrix = vmath::perspective(45.0f,(float)Canvas->W / (float)Canvas->H,1.0f,10000.0f);
};


void CamMain::OnPopupClick(wxCommandEvent &evt)
{
    Functions(evt.GetId());
}


//****************************//
//**
//****************************//
void CamMain::Functions(uint id)
{
    switch(id)
    {
    case f_Copy:
        printf("Copy layer 0\n");
        break;
    case f_Clear:
        I[iNum].Clear();
        break;
    }
    Refresh();

}
